package com;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class LogoutListener implements HttpSessionListener {
	public static final Logger LOG = LoggerFactory.getLogger(LogoutListener.class);

	public LogoutListener() {
	}

	public void sessionCreated(HttpSessionEvent arg0) {
	}

	public void sessionDestroyed(HttpSessionEvent arg0) {

		HttpSession session = arg0.getSession();
		String name = (String) session.getAttribute("nickname");
		ApplicationContext  context = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
		
		LogoutExecutor logoutExecutor = (LogoutExecutor) context.getBean("logoutExecutor");

		try {
			logoutExecutor.logout(name);
		} catch (SQLException | NamingException | IOException e) {
			e.printStackTrace();
		}

		LOG.info("Logged out with name: " + name);
	}


}
